from django.db.models.query_utils import Q
from rest_framework import status, viewsets
from rest_framework.decorators import api_view
from rest_framework.response import Response

from .models import Experiment
from .models import ExperimentalProgram
from .models import ExperimentProcedure
from .models import Riddle

from .serializers import ExperimentSerializers
from .serializers import ExperimentalProgramSerializers
from .serializers import ExperimentProcedureSerializers
from .serializers import RiddleSerializer


# Create your views here.
class ExperimentViewSet(viewsets.ModelViewSet):
    queryset = Experiment.objects.all()
    serializer_class = ExperimentSerializers


class ExperimentalProgramViewSet(viewsets.ModelViewSet):
    queryset = ExperimentalProgram.objects.all()
    serializer_class = ExperimentalProgramSerializers

    def update(self, request, *args, **kwargs):
        # 编辑附件的情况：
        # 1、之前不存在附件，上传附件为新附件，直接添加
        # 2、之前不存在附件，上传附件为空，不处理
        # 3、之前已存在附件，上传附件为新附件，那么需要删除旧的附件，再添加新附件
        # 4、之前已存在附件，上传附件为空，那么需要删除旧的附件
        # 5、之前已存在附件，且未修改上传附件，这种情况已在前端处理，
        # 即不传polarization_curve和polarization_curve_empty参数
        # request.data包含polarization_curve参数说明需要上传新附件
        # request.data包含polarization_curve_empty参数说明上传附件为空
        data = request.data
        if 'impedance' in data or 'impedance_empty' in data:
            self.__delete_exist_file('impedance')
        if 'impedance_curve' in data or 'impedance_curve_empty' in data:
            self.__delete_exist_file('impedance')
        response = super().update(request, args, kwargs)
        return response

    def __delete_exist_file(self, key):
        instance = self.get_object()
        file = getattr(instance, key)
        if file != '':
            file.delete()


class ExperimentProcedureViewSet(viewsets.ModelViewSet):
    queryset = ExperimentProcedure.objects.all()
    serializer_class = ExperimentProcedureSerializers


class RiddleViewSet(viewsets.ModelViewSet):
    """
    允许分析检测查看或编辑的API路径。
    """
    queryset = Riddle.objects.all()
    serializer_class = RiddleSerializer

    def update(self, request, *args, **kwargs):
        # 编辑附件的情况：
        # 1、之前不存在附件，上传附件为新附件，直接添加
        # 2、之前不存在附件，上传附件为空，不处理
        # 3、之前已存在附件，上传附件为新附件，那么需要删除旧的附件，再添加新附件
        # 4、之前已存在附件，上传附件为空，那么需要删除旧的附件
        # 5、之前已存在附件，且未修改上传附件，这种情况已在前端处理，
        # 即不传polarization_curve和polarization_curve_empty参数
        # request.data包含polarization_curve参数说明需要上传新附件
        # request.data包含polarization_curve_empty参数说明上传附件为空
        data = request.data
        if 'riddle_report' in data or 'riddle_report_empty' in data:
            self.__delete_exist_file('riddle_report')
        if 'annex' in data or 'annex_empty' in data:
            self.__delete_exist_file('annex')
        response = super().update(request, args, kwargs)
        return response

    def __delete_exist_file(self, key):
        instance = self.get_object()
        file = getattr(instance, key)
        if file != '':
            file.delete()


@api_view(['GET'])
def get_require_audit_experiment(request):
    """
    获取待审核实验信息
    """
    user = request.user
    # data = Experiment.objects.filter(
    #     Q(experiment_reviewer=user) & Q(approval_status='1')
    # )
    # 所有待审核实验
    data = Experiment.objects.filter(approval_status='1')
    result = []
    for obj in data:
        # 只取课题负责人为当前用户的实验
        if obj.subject_name.subject_principal == user:
            result.append({
                'experiment_id': obj.experiment_id,
                'experiment_name': obj.experiment_name,
                'subject_name': obj.subject_name.subject_name,
                'experiment_num': obj.experiment_num,
                'experimenter': obj.experimenter,
                # 'experiment_reviewer': user.username,
                # 'approval_status': obj.approval_status,
            })
    return Response(result, status=status.HTTP_200_OK)


@api_view(['GET'])
def get_require_audit_experiment_procedure(request):
    """
    获取待审核实验过程
    """
    user = request.user
    # data = ExperimentProcedure.objects.filter(
    #     Q(experiment_procedure_reviewer=user) & Q(approval_status='1')
    # )
    # 所有待审核实验过程
    data = ExperimentProcedure.objects.filter(approval_status='1')
    result = []
    for obj in data:
        # 只取课题负责人为当前用户的实验过程
        if obj.experiment_name.subject_name.subject_principal == user:
            result.append({
                'experiment_procedure_id': obj.experiment_procedure_id,
                'experiment_name': obj.experiment_name.experiment_name,
                'experiment_program_name': obj.experiment_program_name.experiment_program_name,
                'experiment_code': obj.experiment_code,
                'experimental_principle': obj.experimental_principle,
                'experiment_record': obj.experiment_record,
                'experiment_phenomena': obj.experiment_phenomena,
                'raw_material_name': obj.raw_material_name,
                'purity': obj.purity,
                'raw_material_source': obj.raw_material_source,
                'equipment_name': obj.equipment_name,
                'equipment_manufacturer': obj.equipment_manufacturer,
                'device_model': obj.device_model,
                'quantity': obj.quantity,
                'equipment_steps': obj.equipment_steps,
                'sample_num': obj.sample_num,
                'experimental_expectation': obj.experimental_expectation,
                # 'experiment_procedure_reviewer': obj.experiment_procedure_reviewer.username,
            })
    return Response(result, status=status.HTTP_200_OK)


@api_view(['GET'])
def get_passed_experiment(request):
    """
    获取审核通过的实验
    """
    # 所有审核通过的实验
    data = Experiment.objects.filter(approval_status='2')
    result = []
    for obj in data:
        result.append({
            'experiment_id': obj.experiment_id,
            'experiment_name': obj.experiment_name,
        })
    return Response(result, status=status.HTTP_200_OK)
